package com.example.demo.algorithm;

import java.util.Arrays;

/**
 * @ClassName : MergeSortTest
 * @Description : 练习归并排序
 * @Author : wind
 * @Date: 2021-01-28 17:23
 * @Version 1.0
 */
public class MergeSortTest {

    static int[] temp;

    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        temp = new int[arr.length];
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    static void sort(int array[], int left, int right) {
        if (left >= right) {
            return;
        } else {
            int mid = (left + right) / 2;
            sort(array, left, mid);
            sort(array, mid + 1, right);
            merge(array, left, mid, right);
        }
    }

    static void merge(int array[], int left, int mid, int right) {
        int l = left;
        int r = mid + 1;
        int i = left;

        while (l <= mid && r <= right) {
            if (array[l] < array[r]) {
                temp[i++] = array[l++];
            } else {
                temp[i++] = array[r++];
            }
        }
        while (l <= mid) {
            temp[i++] = array[l++];
        }
        if (r <= right) {
            temp[i++] = array[r++];
        }
        for (int j = left; j <= right; j++) {
            System.out.println("left：" + left + " right：" + right);
            array[j] = temp[j];
        }
    }
}
